#include <Arduino.h>
#include <AD7193_SPI.h>
#include "WHT20_I2C.h"

WHT20 WHT20;
AD7193 AD7193;
#define AD7193_EN_PIN 47
void setup()
{
  Serial.begin(115200);
  pinMode(AD7193_EN_PIN, OUTPUT);
  digitalWrite(AD7193_EN_PIN, HIGH);
  Wire.begin(SDA, SCL);
  
  AD7193.begin();

  AD7193.SetPGAGain(1);

  AD7193.reset();

  delayMicroseconds(500);

  AD7193.AppendStatusValuetoData();

  AD7193.setSinc(0); 


  AD7193.SetAverage(16);

  AD7193.SetChop(1); // xiugai
  AD7193.SetRegisterValue(5, 0x40,1, 1);

  AD7193.SetPsuedoDifferentialInputs();
  AD7193.CalibrateFullScale();
  AD7193.ReadRegisterMap();
  Serial.println("\nBegin AD7193 conversion");
}

void loop()
{
  unsigned long Data[8];
  float Voltage[8];

  for (int i = 0; i < 8; i++)
  {
    Data[i] = AD7193.ReadADCChannel(i) >> 8;
    Voltage[i] = AD7193.DataToVoltage(Data[i]);

    // Serial.printf("CH%1d data: 0x%02X\r\n", i, Data[i]);
    // Serial.printf("Channel %1d Voltage Measurement: %4.3f V\r\n", i, Voltage[i]);
  }
  Serial.println();
  Serial.print("Raw Data:\t\t");
  for (int n = 0; n < 8; n++){
    Serial.printf("CH%1d: 0x%02X\t", n + 1, Data[n]);
    
  }
  Serial.println();
  Serial.print("Voltage Measurement:\t");
  for (size_t i = 0; i < 8; i++)
  {
    Serial.printf("CH%1d : %4.3f V\t", i + 1, Voltage[i]);
  }
//   if (WHT20.available() == true)
  if(1)
  {
    // Get the new temperature and humidity value
    float temperature = WHT20.getTemperature();
    float humidity = WHT20.getHumidity();

    // Print the results
    Serial.println();
    Serial.print("Temperature: ");
    Serial.print(temperature, 2);
    Serial.print(" C\t");
    Serial.print("Humidity: ");
    Serial.print(humidity, 2);
    Serial.print("% RH");

    Serial.println();
  }
  delay(1000);
    
}